# --**coding:utf-8**--
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from queryLog.models import IpManage,ApiStats
from queryLog.util import sshClient
# Create your views here.
import paramiko,logging
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
import uiautomator2
logger = logging.getLogger(__name__)
collect_logger = logging.getLogger("collect")
error_logger = logging.getLogger("error")
def index(request):
    return render(request, 'querylog/index.html')

def test(request):

    collect_logger.info("用户1:河南")
    error_logger.error("呵呵呵呵呵呵呵")
    print request.POST
    request.session['k1'] = 123
    print request.COOKIES.keys()
    print request.session.keys()
    print request.session.get('k1')
    resJson = JsonResponse({'name':'test'})
    resJson.set_cookie('abc','mima')

    logger.debug("一个萌萌的请求过来了。。。。")
    logger.info("一个更萌的请求过来了。。。。")
    logger.debug("这是app01里面的index视图函数")
    resJson.set_signed_cookie('abc', 'mima', salt='test',max_age =1)

    return resJson
    # return render(request,'querylog/queryCount.html')
@csrf_exempt
def testreceiveInfo(request):
    name = request.POST.get('name') # 接口名
    codeStatus = request.POST.get('code') # 状态码
    api_id = request.POST.get('api_id') # api_id
    print name,codeStatus,api_id
    localTime = sshClient.timeFormat()  # 获取格式化后的时间
    if codeStatus == '全部': # 查询所有状态码的调用量
        codeDic = {
            '403': '',
            '200': '',
            '401': '',
            '500': '',
            '400': '',
        }
        list = [""" '"http_status":"403"' """, """ '"http_status":"200"' """, """ '"http_status":"401"' """,
                """ '"http_status":"500"' """, """ '"http_status":"400"' """]
        for eachCode in list:
            httpCode = eachCode[17:20]
            # 查询服务器
            # stdin, stdout, stderr = sshClient.register().exec_command(
            #     "cd /home/linkface/log_process_stat/api_logs;  zcat cloud-api.20190716.log.gz | grep '{0}' | grep {1} | wc -l".format(
            #         name, eachCode))
            # codeDic[httpCode] = stdout.read().split('\n')[0]


        # 查询库数量  例:
            print 'name:',name
            print 'localtime:',localTime
            print 'httpcode:',httpCode
            info = ApiStats.objects.filter(api=name, date__icontains=localTime,response_code=httpCode)
            statusCount = 0
            for eachInfo in info:
                print 'eachinfo.count:',eachInfo.count
                statusCount+=eachInfo.count
            print 'statuscount：',statusCount
            codeDic[httpCode + 'database'] = statusCount
        print codeDic
    else: # 仅查询对应的状态码
        pass
    return JsonResponse(codeDic)



@require_http_methods(['GET','POST']) # only support get or post
def creatSSHClient(request):
    '''
    :param request: 机器ip、要查询的接口
    :return: 日志中的记录次数、库中的记录次数
    '''
    ip = request.POST.get('ip')
    interface = request.POST.get('interface')
    # 根据ip去数据库查询对应的账号和密码，若查不到，返回错误给端
    serviceObj = IpManage.objects.filter(ip=ip)
    if serviceObj:
        # 查到机器，获取账号及密码
        for serviceInfo in serviceObj:
            sshClient = paramiko.SSHClient()
            sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # connect service
            sshClient.connect(ip,port=serviceInfo.port,username=serviceInfo.username,password=serviceInfo.pwd)
            # 执行  注意  每次连接仅支持一次查询操作
            sshClient.exec_command('')
            # 查 400、401、403、500、200 次数；查库记录次数；api_id不存在次数 ~ ~ ~

    else:
        return HttpResponse('service ip not found!!')

    # 执行服务器操作  ssh连接样例
    sshClient = paramiko.SSHClient()
    sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshClient.connect('100.66.225.5', port=22, username='linkface', password='linkfaceRD')
    stdin, stdout, stderr = sshClient.exec_command(
        "cd /home/linkface/log_process_stat/api_logs;  zcat cloud-api.20190613.log.gz | grep {0} | grep {1} | wc -l".format(
            """ "/data/verify_id_name" """, """ '"http_status":"500"' """))
    # transport连接样例
    trans = paramiko.Transport('100.66.225.5', 22)
    trans.connect(username='linkface',password='linkfaceRD')
    ssh = paramiko.SSHClient()
    ssh._transport = trans
    stdin, stdout, stderr = ssh.exec_command('linux command')

    return HttpResponse(stdout.read())

def testQuery(request):
    # sshClient = paramiko.SSHClient()
    # sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # sshClient.connect('100.66.225.5', port=22, username='linkface', password='linkfaceRD')
    sshclient = sshClient.register()
    codeDic = {
        '403':'',
        '200':'',
        '401':'',
        '500':'',
        '400':'',
    }
    list = [""" '"http_status":"403"' """,""" '"http_status":"200"' """,""" '"http_status":"401"' """,""" '"http_status":"500"' """,""" '"http_status":"400"' """]
    for eachCode in list:
        httpCode = eachCode[17:20]
        stdin, stdout, stderr = sshclient.exec_command(
            "cd /home/linkface/log_process_stat/api_logs;  zcat cloud-api.20190716.log.gz | grep {0} | grep {1} | wc -l".format(
                """ "/data/verify_id_name_bankcard_phone" """, eachCode))
        codeDic[httpCode] = stdout.read()
        print stdout.read()
    print codeDic

    # linux_command = """ cd /home/linkface/log_process_stat/api_logs;  zcat cloud-api.20190716.log.gz | grep {0} | grep '"http_status":{1}' | wc -l """.format(
    #     """ "/data/verify_id_name_bankcard_phone" """, """ "200" """)
    pass


